<template>
  <div class="app">
    <el-card class="box-card">
      <template #header>面经后台管理</template>
      <el-form :model="form" :rules="rules" ref="ruleForm">
        <el-form-item prop="username" label="用户名">
          <el-input type="text" v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item prop="password" label="密码">
          <el-input type="password" v-model="form.password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="allPattern" >登录</el-button>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { login } from '@/api/user'
export default {
  name: 'HmElementPcIndex',
  data () {
    return {
      form: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 6, max: 15, message: '用户名必须为 6 ~ 15 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { pattern: /^\w{5,10}$/, message: '密码必须为 5 ~ 10 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    allPattern () {
      this.$refs.ruleForm.validate(async valid => {
        console.log(valid)
        if (!valid) return
        // console.log('发送请求')
        const res = await login(this.form)
        // 数据脱壳
        this.$store.commit('user/setUserToken', res.data.token)
        // 跳转至首页
        this.$router.push('/')
        // 提醒用户登录成功
        this.$message.success('登陆成功')
      })
    },
    reset () {
      // 重置表单, 会移除所有异常字段
      this.$refs.ruleForm.resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
.app {
  display: flex;
  background: url(../../assets/login-bg.svg) no-repeat center / cover;
  .box-card {
    width: 420px;
    margin: 100px auto;
    ::v-deep .el-card__header {
      background-color: #727cf5;
      text-align: center;
      color: white;
    }
  }
}
</style>
